<route lang="json5">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '',
  },
}
</route>

<template>
  <view>
    <wd-popup
      v-model="showPopup"
      position="bottom"
      :safe-area-inset-bottom="true"
      custom-style="height: 450px;"
    >
      <view class="h-400rpx p-40rpx">
        <view class="flex items-center">
          <image class="w-100rpx h-100rpx rounded" mode="heightFix" :src="logo"></image>
          <text class="text-xl ml-5 font-bold">{{ title }}</text>
        </view>
        <view class="mt-5 text-muted">建议使用您的微信头像和昵称，以便获得更好的体验</view>
        <view class="mt-30rpx">
          <wd-form :model="formDataModel" ref="form">
            <wd-cell title="头像" title-width="100px">
              <wd-upload
                :file-list="formDataModel.avatarList"
                :limit="1"
                :upload-method="customUpload"
                @success="handleFileSuccess"
                @fail="handleFileFail"
                prop="avatarList"
              >
                <!-- <wd-button type="primary" shape="round" size="small">上传头像</wd-button> -->
              </wd-upload>
            </wd-cell>

            <wd-cell title="昵称" title-width="100px">
              <wd-input
                v-model="formDataModel.nickname"
                name="nickname"
                type="text"
                placeholder="请输入昵称"
                prop="nickname"
              />
            </wd-cell>

            <view class="mt-80rpx">
              <wd-button type="primary" @click="handleSubmit" block>确定</wd-button>
            </view>
            <view class="flex justify-center mt-60rpx">
              <view class="text-muted" @click="showPopup = false">暂不登录</view>
            </view>
          </wd-form>
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<script lang="ts" setup>
import { computed, ref, reactive } from 'vue'
import { getEnvBaseUploadUrl } from '@/utils/index'
const props = defineProps({
  show: Boolean,
  logo: String,
  title: String,
})

const form = ref()

const emit = defineEmits<{
  (event: 'update:show', show: boolean): void
  (event: 'update', value: any): void
}>()

const showPopup = computed({
  get() {
    return props.show
  },
  set(val) {
    emit('update:show', val)
  },
})

const formDataModel = reactive({ nickname: '', avatarList: [], avatar: '' })

const handleFileSuccess = ({ file, fileList, formData }) => {
  console.log('file:', file)
  console.log('fileList:', fileList)
  console.log('formData:', formData)
  if (fileList.length > 0) {
    formDataModel.avatarList = fileList
    const resp = fileList[0].response
    console.log('上传响应:', resp)
    const respJson = JSON.parse(resp)
    // response: "{"code":200,"msg":"成功","data":{"id":155,"cid":0,"type":10,"name":"IXTHvHO0OUNn23b148f8166276880b99085fb0754833.png","url":"image/20250527/0bc80575-50bf-40e7-9bbb-5f5d67fdd654.png","uri":"http://192.168.1.14:8084/api/uploads/image/20250527/0bc80575-50bf-40e7-9bbb-5f5d67fdd654.png"},"show":0}"
    if (respJson && respJson.code === 200) {
      // 假设返回的文件对象有url或path属性
      formDataModel.avatar = respJson.data.url
    } else {
      uni.showToast({
        title: '上传失败，请重试',
        icon: 'none',
      })
      formDataModel.avatar = ''
    }
  } else {
    formDataModel.avatar = ''
  }
}

const handleFileFail = ({ error, file, formData }) => {
  console.error('上传失败:', error, file)
  formDataModel.avatarList = []
  formDataModel.avatar = ''
}

const customUpload = async (file, formData, options) => {
  const url = getEnvBaseUploadUrl()
  console.log('自定义上传url:', url)
  const uploadTask = uni.uploadFile({
    url,
    header: options.header,
    name: options.name,
    fileName: options.name,
    fileType: options.fileType,
    formData,
    filePath: file.url,
    success(res) {
      if (res.statusCode === options.statusCode) {
        // 设置上传成功
        options.onSuccess(res, file, formData)
      } else {
        // 设置上传失败
        options.onError({ ...res, errMsg: res.errMsg || '' }, file, formData)
      }
    },
    fail(err) {
      // 设置上传失败
      options.onError(err, file, formData)
    },
  })
  // 设置当前文件加载的百分比
  uploadTask.onProgressUpdate((res) => {
    options.onProgress(res, file)
  })
}

const handleSubmit = () => {
  console.log('提交数据:', formDataModel)

  if (!formDataModel.avatar) {
    uni.showToast({
      title: '请上传头像',
      icon: 'none',
    })
    return
  }
  if (!formDataModel.nickname) {
    uni.showToast({
      title: '请输入昵称',
      icon: 'none',
    })
    return
  }
  emit('update', formDataModel)
}
</script>

<style lang="scss" scoped>
// 可根据需要自定义样式
</style>
